import { defineStore } from 'pinia'
import { getToken, setToken, removeToken } from '@/utils/storage'
import { login as loginApi, logout as logoutApi } from '@/api/auth'

/**
 * 用户认证状态管理
 */
export const useAuthStore = defineStore('auth', {
  state: () => ({
    token: getToken() || '',
    userInfo: null,
    roles: []
  }),

  getters: {
    // 是否已登录
    isLoggedIn: (state) => !!state.token,

    // 获取token
    userToken: (state) => state.token,

    // 获取用户信息
    userInfo: (state) => state.userInfo,

    // 获取角色列表
    roles: (state) => state.roles,

    // 获取用户名
    username: (state) => state.userInfo?.username || '',

    // 获取真实姓名
    realName: (state) => state.userInfo?.realName || '',

    // 获取角色名称
    roleName: (state) => state.userInfo?.roleName || '',

    // 获取用户ID
    userId: (state) => state.userInfo?.userId || null,

    // 检查是否有指定角色
    hasRole: (state) => (role) => {
      return state.roles.includes(role)
    },

    // 检查是否为管理员
    isAdmin: (state) => state.roles.includes('管理员'),

    // 检查是否为老师
    isTeacher: (state) => state.roles.includes('老师'),

    // 检查是否为学生
    isStudent: (state) => state.roles.includes('学生'),

    // 检查是否为裁判
    isReferee: (state) => state.roles.includes('裁判'),

    // 检查是否为志愿者
    isVolunteer: (state) => state.roles.includes('志愿者')
  },

  actions: {
    // 设置token
    setToken(token) {
      this.token = token
    },

    // 设置用户信息
    setUserInfo(userInfo) {
      this.userInfo = userInfo
    },

    // 设置角色
    setRoles(roles) {
      this.roles = roles
    },

    // 清除用户信息
    clearUser() {
      this.token = ''
      this.userInfo = null
      this.roles = []
    },

    // 用户登录
    async login(loginData) {
      try {
        const response = await loginApi(loginData)
        const { token, userId, username, realName, roleName, roleId } = response.data

        // 保存token到本地存储
        setToken(token, loginData.remember)

        // 更新状态
        this.setToken(token)

        // 保存用户信息
        const userInfo = { userId, username, realName, roleName, roleId }
        this.setUserInfo(userInfo)
        this.setRoles([roleName])

        return response
      } catch (error) {
        console.error('登录失败:', error)
        throw error
      }
    },

    // 获取用户信息
    async getUserInfo() {
      try {
        if (!this.token) {
          throw new Error('未找到token')
        }

        // 这里可以调用获取用户信息的API
        // const response = await getUserInfoApi()
        // this.setUserInfo(response.data)
        // this.setRoles(response.data.roles)

        return this.userInfo
      } catch (error) {
        console.error('获取用户信息失败:', error)
        throw error
      }
    },

    // 用户登出
    async logout() {
      try {
        // 调用登出API
        await logoutApi()
      } catch (error) {
        console.error('登出API调用失败:', error)
      } finally {
        // 清除本地存储
        removeToken()
        // 清除状态
        this.clearUser()
      }
    },

    // 重置token
    resetToken() {
      removeToken()
      this.clearUser()
    },

    // 刷新用户信息
    async refreshUserInfo() {
      try {
        const userInfo = await this.getUserInfo()
        return userInfo
      } catch (error) {
        // 如果获取用户信息失败，清除登录状态
        this.resetToken()
        throw error
      }
    },

    // 更新用户信息
    updateUserInfo(newUserInfo) {
      this.userInfo = { ...this.userInfo, ...newUserInfo }
    }
  },

  // 持久化配置（可选，如果需要使用pinia-plugin-persistedstate）
  persist: {
    key: 'auth-store',
    storage: localStorage,
    paths: ['token', 'userInfo', 'roles']
  }
})